package net.hn.hnms.biz.plan.group.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import net.hn.hnms.biz.plan.domain.MineNumber;
import net.hn.hnms.biz.plan.domain.TreeStringEntity;
import net.hn.hnms.biz.plan.enums.DataType;
import net.hn.hnms.biz.plan.group.service.GroupStatisticService;
import net.hn.hnms.biz.plan.mapper.DimShiftMapper;
import net.hn.hnms.biz.plan.mapper.GroupStatisticMapper;
import net.hn.hnms.biz.plan.request.DimMiningFaceReq;
import net.hn.hnms.biz.plan.request.OpencastAndUndergroundMiningReq;
import net.hn.hnms.biz.plan.request.SaleAnalyseReq;
import net.hn.hnms.biz.plan.service.IDimMiningFaceService;
import net.hn.hnms.biz.plan.vo.*;
import net.hn.hnms.sys.common.core.constant.Constants;
import net.hn.hnms.sys.common.core.enums.CoalInfo;
import net.hn.hnms.sys.common.core.exception.HuaNengException;
import net.hn.hnms.sys.common.core.utils.DateUtils;
import net.hn.hnms.sys.common.core.utils.StringUtils;
import net.hn.hnms.sys.common.redis.domain.SysOrganizationVo;
import net.hn.hnms.sys.common.redis.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.math.BigDecimal.ROUND_CEILING;
import static java.math.BigDecimal.ROUND_HALF_UP;



@Service
public class GroupStatisticServiceImpl implements GroupStatisticService {
    @Autowired
    private GroupStatisticMapper groupStatisticMapper;

    @Autowired
    private IDimMiningFaceService dimMiningFaceService;


    @Autowired
    private DimShiftMapper dimShiftMapper;

    static final List<String> order = Arrays.asList("总计","华亭煤业", "扎煤公司", "陕西矿业", "庆阳煤电", "滇东公司");


    @Override
    public List<PlanStatisticVO> monthoutput(Integer month) {
        ArrayList<PlanStatisticVO> planStatisticVOS = new ArrayList<>();
        LocalDate date = LocalDate.now();
// 获得当前的月和日
        if (month == null || (month > 12 && month < 0)) {
            month = date.getMonthValue();
        }
        Date[] dateRange = DateUtils.getDateRange(null, month);

        List<String> companyCodes = groupStatisticMapper.selectcompanyCode();
        if (companyCodes !=null){
            for (String companyCode : companyCodes) {
                PlanStatisticVO planStatisticVO = new PlanStatisticVO();
                PlanCompleteStatisticVO completeInfo = groupStatisticMapper.planComplete3(dateRange[0], dateRange[1], companyCode);
                planStatisticVO.setCompanyName(companyCode);
                planStatisticVO.setPlanTotal(completeInfo.getPlanOutput().divide(Constants.TEN_THOUSAND, 2, RoundingMode.CEILING));
                planStatisticVO.setCompleteTotal(completeInfo.getOutput().divide(Constants.TEN_THOUSAND, 2, RoundingMode.CEILING));
                planStatisticVOS.add(planStatisticVO);
            }
        }
        return planStatisticVOS;
    }
    @Override
    public List<PlanStatisticVO> yearoutput() {
        ArrayList<PlanStatisticVO> planStatisticVOS = new ArrayList<>();
        int year = DateUtil.year(new Date());
        Date beginDate = DateUtil.beginOfDay(DateUtil.parseDate(year + "-01-01"));
        Date endDate = DateUtil.endOfDay(DateUtil.parseDate(year + "-12-31"));


        List<String> companyCodes = groupStatisticMapper.selectcompanyCode();
        if (companyCodes !=null){
            for (String companyCode : companyCodes) {
                PlanStatisticVO planStatisticVO = new PlanStatisticVO();
                PlanCompleteStatisticVO completeInfo = groupStatisticMapper.planComplete3(beginDate, endDate, companyCode);
                planStatisticVO.setCompanyName(companyCode);
                planStatisticVO.setPlanTotal(completeInfo.getPlanOutput().divide(Constants.TEN_THOUSAND, 2, RoundingMode.CEILING));
                planStatisticVO.setCompleteTotal(completeInfo.getOutput().divide(Constants.TEN_THOUSAND, 2, RoundingMode.CEILING));
                planStatisticVOS.add(planStatisticVO);
            }
        }
        return planStatisticVOS;
    }


    @Override
    public List<PlanStatisticVO> outputCountmonthAndYear(Integer month, String companyCode) {
        ArrayList<PlanStatisticVO> list = new ArrayList<>();
        LocalDate date = LocalDate.now();
// 获得当前的月和日
        if (month == null || (month > 12 && month < 0)) {
            month = date.getMonthValue();
        }
        Date[] dateRange = DateUtils.getDateRange(null, month);
        PlanCompleteStatisticVO completeInfo = groupStatisticMapper.planComplete3(dateRange[0], dateRange[1], companyCode);
        PlanStatisticVO planStatisticVO = new PlanStatisticVO();
        PlanStatisticVO planStatisticVO2 = new PlanStatisticVO();

        int year = DateUtil.year(new Date());
        Date beginDate = DateUtil.beginOfDay(DateUtil.parseDate(year + "-01-01"));
        Date endDate = DateUtil.endOfDay(DateUtil.parseDate(year + "-12-31"));
        PlanCompleteStatisticVO completeInfo2 = groupStatisticMapper.planComplete3(beginDate, endDate, companyCode);

        planStatisticVO.setDataName("月产");
        planStatisticVO.setPlanTotal(completeInfo.getPlanOutput().divide(Constants.TEN_THOUSAND, 2, RoundingMode.CEILING));
        planStatisticVO.setCompleteTotal(completeInfo.getOutput().divide(Constants.TEN_THOUSAND, 2, RoundingMode.CEILING));
        BigDecimal decimal = new BigDecimal(0);
        if (completeInfo.getPlanOutput().compareTo(new BigDecimal(0)) != 0) {
            decimal = (completeInfo.getOutput().divide(completeInfo.getPlanOutput(), 2, RoundingMode.HALF_UP).multiply(new BigDecimal(100))).setScale(0, ROUND_HALF_UP);
        }
        planStatisticVO.setPercent(decimal);
        list.add(planStatisticVO);
        planStatisticVO2.setDataName("年产");
        planStatisticVO2.setPlanTotal(completeInfo2.getPlanOutput().divide(Constants.TEN_THOUSAND, 2, RoundingMode.CEILING));
        planStatisticVO2.setCompleteTotal(completeInfo2.getOutput().divide(Constants.TEN_THOUSAND, 2, RoundingMode.CEILING));
        BigDecimal decimal2 = new BigDecimal(0);
        if (completeInfo2.getPlanOutput().compareTo(new BigDecimal(0)) != 0) {
            decimal2 = (completeInfo2.getOutput().divide(completeInfo2.getPlanOutput(), 2, RoundingMode.HALF_UP).multiply(new BigDecimal(100))).setScale(0, ROUND_HALF_UP);
        }
        planStatisticVO2.setPercent(decimal2);
        list.add(planStatisticVO2);

        return list;
    }

    @Override
    public Map<String, PlanStatisticVO> planComplete(Integer month, String companyCode) {
        //获得起始日期
        Date[] dateRange = DateUtils.getDateRange(null, month);

        PlanCompleteStatisticVO completeInfo = groupStatisticMapper.planComplete(dateRange[0], dateRange[1],companyCode);
        Map<String, PlanStatisticVO> result = new HashMap<>();
        result.put(DataType.DEVELOP.name(), createPlanComplete(DataType.DEVELOP, completeInfo.getPlanDevelopment(), completeInfo.getDevelopment()));
        result.put(DataType.DRIVAGE.name(), createPlanComplete(DataType.DRIVAGE, completeInfo.getPlanDrivage(), completeInfo.getDrivage()));
        result.put(DataType.MINING.name(), createPlanComplete(DataType.MINING, completeInfo.getPlanMining(), completeInfo.getMining()));
        result.put(DataType.SALE.name(), createPlanComplete(DataType.SALE, completeInfo.getPlanOutput().divide(Constants.TEN_THOUSAND, 2, RoundingMode.CEILING), completeInfo.getOutput().divide(Constants.TEN_THOUSAND, 2, RoundingMode.CEILING)));
        //result.put(DataType.SALE.name(), createPlanComplete(DataType.SALE, completeInfo.getPlanOutput(), completeInfo.getOutput()));
        result.put(DataType.WASHING.name(), createPlanComplete(DataType.WASHING, completeInfo.getPlanWashing().divide(Constants.TEN_THOUSAND, 2, RoundingMode.CEILING), completeInfo.getWashing().divide(Constants.TEN_THOUSAND, 2, RoundingMode.CEILING)));
        result.put(DataType.PEEL.name(), createPlanComplete(DataType.PEEL, completeInfo.getPlanPeel().divide(Constants.TEN_THOUSAND, 2, RoundingMode.CEILING), completeInfo.getPeel().divide(Constants.TEN_THOUSAND, 2, RoundingMode.CEILING)));
        return result;
    }

    @Override
    public FootAgeVo peelCount(Integer month, String companyCode) {
        if (month == null || (month >12&&month<0)){
            LocalDate date = LocalDate.now();
            month = date.getMonthValue();
        }
        FootAgeVo completeInfo = new FootAgeVo();
        if (month != null){

            Date[] dateRange = DateUtils.getDateRange(null, month);
            completeInfo = groupStatisticMapper.peelCount(dateRange[0], dateRange[1],companyCode);

        }
        return completeInfo;
    }

    @Override
    public MonthValue annualSituation(String companyCode) {
        return groupStatisticMapper.annualSituation(companyCode);
    }

    @Override
    public List<MiningContinuationVo> faceCondition(String companyCode, String mineCode, Integer type) {
        List<MiningContinuationVo> miningContinuationVos = new ArrayList<>();
        try {
            DynamicDataSourceContextHolder.push("slave");
            miningContinuationVos = groupStatisticMapper.faceCondition(companyCode, mineCode,type);
            if(type==null){
                miningContinuationVos.stream().distinct().forEach(item ->{

                    item.setCompanyNames(item.getCompanyCode());
                    item.setMineNames(item.getMineCode());
                    //根据矿编码查询工作面名称、搬家到面至、结束时间
                    DimMiningFaceReq dimMiningFaces = new DimMiningFaceReq();
                    dimMiningFaces.setMineCode(item.getMineCode());
                    List<DimMiningFaceVO> dimMiningFaceVOS = dimMiningFaceService.selectList(dimMiningFaces);
                    item.setMiningFaceVOS(dimMiningFaceVOS);
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            DynamicDataSourceContextHolder.clear();
        }
        return miningContinuationVos;
    }

    @Override
    public List<DimMiningFaceVO> faceConditionContinuation(String companyCode, String mineCode, Integer type) {
        List<DimMiningFaceVO> dimMiningFaceVOS = new ArrayList<>();
        try {
            DynamicDataSourceContextHolder.push("slave");
            DimMiningFaceReq dimMiningFaces = new DimMiningFaceReq();
            dimMiningFaces.setStatus("0");
            dimMiningFaces.setCompanyCode(companyCode);
            dimMiningFaces.setMineCode(mineCode);
            dimMiningFaceVOS = dimMiningFaceService.selectList(dimMiningFaces);
            dimMiningFaceVOS.stream().distinct().forEach(item->{
                item.setMineNames(item.getMineCode());
                item.setCompanyNames(item.getCompanyCode());
            });

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            DynamicDataSourceContextHolder.clear();
        }

        return dimMiningFaceVOS;
    }


    @Override
    public MonthYieldVo outputStatistic(Integer month, String companyCode) {
        Date d = null;
        if (month == null || (month >12&&month<0)){
            //当前时间前一天
            Calendar cal=Calendar.getInstance();
            cal.add(Calendar.DATE,-1);
            d = cal.getTime();
        }
        //如果月是当前月就用昨天，不是当前月就用月的最后一天
        MonthYieldVo planCompleteStatisticVO = null;
        Date[] dateRange = null;
        if (month != null){
            LocalDate date = LocalDate.now();
            Integer months = date.getMonthValue();
            if(months == month){
                Calendar cal=Calendar.getInstance();
                cal.add(Calendar.DATE,-1);
                d = cal.getTime();
            }else{
                dateRange = DateUtils.getDateRange(null, month);
                d = dateRange[1];
            }
        }
//        LocalTime currentTime = LocalTime.now();
//        if (currentTime.isBefore(LocalTime.of(10, 0))) {
//            // 当前时间在上午10点之前
//            Calendar cal = Calendar.getInstance();
//            cal.setTime(d);
//            cal.add(Calendar.DATE, -1);
//            d = cal.getTime();
//        }
        Date[] yoy = DateUtils.getYOY(d);
        Date[] now = DateUtils.getDateRange(null, null);
        BigDecimal yearYoy = groupStatisticMapper.outputStatisticYoy(yoy[0], yoy[1], now[0], d, companyCode);
        BigDecimal monthYoy = groupStatisticMapper.outputStatisticYoy(yoy[2], yoy[3], yoy[4], yoy[5], companyCode);
        planCompleteStatisticVO = groupStatisticMapper.outputStatistic(d, companyCode);
        if(planCompleteStatisticVO!=null){
            planCompleteStatisticVO.setYearYoy(yearYoy);
            planCompleteStatisticVO.setMonthYoy(monthYoy);
        }else{
            planCompleteStatisticVO = new MonthYieldVo();
            planCompleteStatisticVO.setYearYoy(yearYoy);
            planCompleteStatisticVO.setMonthYoy(monthYoy);
        }
        BigDecimal provedOutput = groupStatisticMapper.getGroupProvedOutput(companyCode);
        planCompleteStatisticVO.setProvedOutput(provedOutput);
        return planCompleteStatisticVO;
    }

    @Override
    public List<MonthYieldVo> outputStatisticDetail(Integer month, String companyCode) {

        Date d = null;
        if (month == null || (month >12&&month<0)){
            //当前时间前一天
            Calendar cal=Calendar.getInstance();
            cal.add(Calendar.DATE,-1);
            d = cal.getTime();



            Calendar tenAM = Calendar.getInstance();
            tenAM.set(Calendar.HOUR_OF_DAY, 10);
            tenAM.set(Calendar.MINUTE, 0);
            tenAM.set(Calendar.SECOND, 0);
            tenAM.set(Calendar.MILLISECOND, 0);

            // 判断当前时间是否超过上午10点
            if (new Date().before(tenAM.getTime())) {
                // 如果当前时间未超过上午10点，则将时间减去一天
                cal.add(Calendar.DATE, -1);
            }

            // 获取修改后的时间
            d = cal.getTime();
        }
        //如果月是当前月就用昨天，不是当前月就用月的最后一天
        MonthYieldVo planCompleteStatisticVO = null;
        Date[] dateRange = null;
        if (month != null){
            LocalDate date = LocalDate.now();
            Integer months = date.getMonthValue();
            if(months == month){
                Calendar cal=Calendar.getInstance();
                cal.add(Calendar.DATE,-1);
                d = cal.getTime();
            }else{
                dateRange = DateUtils.getDateRange(null, month);
                d = dateRange[1];
            }
        }
        Date[] yoy = DateUtils.getYOY(d);
        Date[] now = DateUtils.getDateRange(null, null);
        List<MonthYieldVo> list  = null;

        list = groupStatisticMapper.outputStatisticDetailed(d, companyCode);
        List<MonthYieldVo> yearYoy = groupStatisticMapper.outputStatisticYoyDetailed(yoy[0], yoy[1], now[0], d, companyCode);
        List<MonthYieldVo> monthYoy = groupStatisticMapper.outputStatisticYoyDetailed(yoy[2], yoy[3], yoy[4], yoy[5], companyCode);
            if(list!=null){
                list.stream().distinct().forEach(item ->{
                    yearYoy.stream().distinct().forEach(item1 ->{
                        if(item.getMineCode().equals(item1.getMineCode())){
                            item.setYearYoy(item1.getYearYoy());
                        }
                    });
                    monthYoy.stream().distinct().forEach(item2 ->{
                        if(item.getMineCode().equals(item2.getMineCode())){
                            item.setMonthYoy(item2.getYearYoy());
                        }
                    });
                    item.setCompanyNames(item.getCompanyCode());
                    item.setCompanyNameRe(item.getCompanyCode());
                    item.setMineNames(item.getMineCode());
                });
            }


        return list;
    }

    @Override
    public  List<TreeStringEntity<MonthYieldVo>> outputStatisticConverge(Integer month, String company) {
        List<MonthYieldVo> monthYieldVos = outputStatisticDetail(null, null);


//        Set<String> companyCodes = CoalInfo.getCompanyCodes();


    // 创建 Map 用于存储父子级关系，以煤矿编码为键，公司编码列表为值
        Map<String, List<String>> parentChildMap = new HashMap<>();

    // 遍历原始数据集合
        for (MonthYieldVo monthYieldVo : monthYieldVos) {
            String mineCode = monthYieldVo.getMineCode();
            String companyCode = monthYieldVo.getCompanyCode();

            // 判断父级是否已存在，如果不存在则创建新的父级
            if (!parentChildMap.containsKey(companyCode)) {
                parentChildMap.put(companyCode, new ArrayList<>());
            }

            // 将公司编码添加到对应的父级下
            parentChildMap.get(companyCode).add(mineCode);
        }

        // 构建 TreeEntity 对象并填充数据
        List<TreeStringEntity<MonthYieldVo>> treeEntities = new ArrayList<>();
        for (Map.Entry<String, List<String>> entry : parentChildMap.entrySet()) {
            String companyCodes = entry.getKey();
            List<String> mineCode = entry.getValue();

            TreeStringEntity<MonthYieldVo> treeStringEntity = new TreeStringEntity<>();
            treeStringEntity.setParentId(companyCodes); // 设置父级煤矿编码
            // 这里假设煤矿编码即为父级名称
            treeStringEntity.setParentName(CoalInfo.getCompanyNameByCompanyCode(companyCodes));
//            treeStringEntity.setChildren(mineCode); // 设置子公司编码列表作为子级数据

            // 将 List<MonthYieldVo> 转换为适当的字符串形式，然后设置为子级数据
            BigDecimal daybigDecimal = new BigDecimal("0");
            BigDecimal monthbigDecimal = new BigDecimal("0");
            BigDecimal yearbigDecimal = new BigDecimal("0");
            List<MonthYieldVo> childData = new ArrayList<>();
            for (MonthYieldVo monthYieldVo : monthYieldVos) {
                // 假设 MonthYieldVo 中有一个属性用于表示的字符串，比如 name 属性
                if(monthYieldVo.getCompanyCode().equals(companyCodes)){
                    childData.add(monthYieldVo);
                    daybigDecimal = daybigDecimal.add(monthYieldVo.getTodayQuantity());
                    monthbigDecimal = monthbigDecimal.add(monthYieldVo.getOutput());
                    yearbigDecimal = yearbigDecimal.add(monthYieldVo.getYearCumulativeCompletion());
                    treeStringEntity.setDayOutput(daybigDecimal);
                    treeStringEntity.setMonthOutput(monthbigDecimal);
                    treeStringEntity.setYearOutput(yearbigDecimal);
                }
            }
            treeStringEntity.setChildren(childData);


            // 添加到 TreeEntity 集合中
            treeEntities.add(treeStringEntity);
        }


        return treeEntities;
    }

    @Override
    public List<PlanStatisticVO>  outputStatisticDetailed(Integer month,Integer type, String companyCode) {
        Date d = null;
        if (month == null || (month >12&&month<0)){
            //当前时间前一天
            Calendar cal=Calendar.getInstance();
            cal.add(Calendar.DATE,-1);
            d = cal.getTime();
        }
        //如果月是当前月就用昨天，不是当前月就用月的最后一天
        Date[] dateRange = null;
        if (month != null){
            LocalDate date = LocalDate.now();
            Integer months = date.getMonthValue();
            if(months == month){
                Calendar cal=Calendar.getInstance();
                cal.add(Calendar.DATE,-1);
                d = cal.getTime();
            }else{

                dateRange = DateUtils.getDateRange(null, month);
                d = dateRange[1];
            }
        }
        if(type==2){
            Calendar cal=Calendar.getInstance();
            cal.add(Calendar.DATE,-1);
            d = cal.getTime();
        }
        int daysOfMonth = DateUtils.getDaysOfMonth(d);
        List<PlanStatisticVO> planStatisticVOS = null;
        if(type==null||type==1){
            planStatisticVOS = groupStatisticMapper.outputOfMonthStatisticDetailed(d,companyCode);
        }else if(type == 2){
            planStatisticVOS = groupStatisticMapper.outputOfYearStatisticDetailed(d,companyCode);
        }else if(type == 3){
            planStatisticVOS = groupStatisticMapper.outputOfYearStatisticDetailedOfMineCode(d,daysOfMonth,companyCode);
        }

        if(planStatisticVOS!=null&&type!=3){
            planStatisticVOS.stream().distinct().forEach(item ->{
                item.setCompanyNames(item.getDataCode());
            });
        }else if(planStatisticVOS!=null&&type==3){
            planStatisticVOS.stream().distinct().forEach(item ->{
                item.setMineNames(item.getDataCode());
            });
        }
        return planStatisticVOS;
    }

    @Override
    public Map<String, BigDecimal[]> getProduction(Integer type, Integer level,String companyCode) {
        Map<String, BigDecimal[]> resultMap = new HashMap<>();
        LinkedHashMap<String, BigDecimal[]> updatedResultMap = new LinkedHashMap<>();
        List<MonthYieldVo> monthYieldVos = outputStatisticDetail(null, null);
        if((type == 1 && level == 1)||(type == 1 && level == 2)||(type == 1 && level == 3)){//煤业层级年角度 ， 3个煤业，
            List<String> targetCompanyCodes = new ArrayList<>(Arrays.asList("91150100767874571R", "911507001151964613"));
            // 各矿每年产量，筛选汇总出三个煤业得产量
            resultMap.put("煤业公司", new BigDecimal[]{BigDecimal.ZERO, BigDecimal.ZERO});
            for (MonthYieldVo monthYieldVo : monthYieldVos) {
                BigDecimal yearCumulativeCompletion = BigDecimal.ZERO;
                BigDecimal planOut = BigDecimal.ZERO;
                if(type == 1 && level == 1){
                    yearCumulativeCompletion = monthYieldVo.getYearCumulativeCompletion();
                    planOut =planOut.add( monthYieldVo.getPlanOutPuts());
                } else if (type == 1 && level == 2) {
                    yearCumulativeCompletion = monthYieldVo.getOutput();//月
                    planOut = monthYieldVo.getPlanOutput();
                }else{
                    yearCumulativeCompletion = monthYieldVo.getTodayQuantity();//日
                    planOut = monthYieldVo.getPlanOutputDay();
                }
                if (targetCompanyCodes.contains(monthYieldVo.getCompanyCode())) {
                    if (resultMap.containsKey(monthYieldVo.getCompanyNameRe())) {
                        BigDecimal[] previousValue = resultMap.get(monthYieldVo.getCompanyNameRe());
                        BigDecimal newActualValue = previousValue[0].add(yearCumulativeCompletion);
                        BigDecimal newPlanValue = previousValue[1].add(planOut);
                        resultMap.put(monthYieldVo.getCompanyNameRe(), new BigDecimal[]{newActualValue, newPlanValue});
                    } else {
                        resultMap.put(monthYieldVo.getCompanyNameRe(), new BigDecimal[]{yearCumulativeCompletion, planOut});
                    }
                }else{
                    BigDecimal[] previousValue = resultMap.get("煤业公司");
                    BigDecimal newActualValue = previousValue[0].add(yearCumulativeCompletion);
                    BigDecimal newPlanValue = previousValue[1].add(planOut);
                    resultMap.put("煤业公司", new BigDecimal[]{newActualValue, newPlanValue});
                }
            }
            List<String> sortOrder = Arrays.asList("煤业公司", "北方公司", "蒙东公司");

            for (String key : sortOrder) {
                if (resultMap.containsKey(key)) {
                    updatedResultMap.put(key, resultMap.get(key));
                }
            }
        }
        else if ((type == 2 && level == 1)||(type == 2 && level == 2)||(type == 2 && level == 3)) {//华亭煤业、庆阳煤电、陕西矿业、扎煤公司、滇东公司
            List<String> targetCompanyCodes2 = new ArrayList<>(Arrays.asList("916200002258722645",
                    "91610132311043067B",
                    "91150781720169744B",
                    "91530325346622296C",
                    "91621000566400003E"));
            for (MonthYieldVo monthYieldVo : monthYieldVos) {
                BigDecimal yearCumulativeCompletion = BigDecimal.ZERO;
                BigDecimal planOut = BigDecimal.ZERO;
                if(type == 2 && level == 1){
                    yearCumulativeCompletion = monthYieldVo.getYearCumulativeCompletion();
                    planOut = monthYieldVo.getPlanOutPuts();
                } else if (type == 2 && level == 2) {
                    yearCumulativeCompletion = monthYieldVo.getOutput();//月
                    planOut = monthYieldVo.getPlanOutput();
                }else{
                    yearCumulativeCompletion = monthYieldVo.getTodayQuantity();//日
                    planOut = monthYieldVo.getPlanOutputDay();
                }
                if (targetCompanyCodes2.contains(monthYieldVo.getCompanyCode())) {
                    if (resultMap.containsKey(monthYieldVo.getCompanyNameRe())) {
                        BigDecimal[] previousValue = resultMap.get(monthYieldVo.getCompanyNameRe());
                        BigDecimal newActualValue = previousValue[0].add(yearCumulativeCompletion);
                        BigDecimal newPlanValue = previousValue[1].add(planOut);
                        resultMap.put(monthYieldVo.getCompanyNameRe(), new BigDecimal[]{newActualValue, newPlanValue});
                    } else {
                        resultMap.put(monthYieldVo.getCompanyNameRe(), new BigDecimal[]{yearCumulativeCompletion, planOut});
                    }
                }
            }
//            if (!resultMap.containsKey("滇东公司")) {
//                resultMap.put("滇东公司", new BigDecimal[]{new BigDecimal("0"),new BigDecimal("0")});
//            }
            List<String> sortOrder = Arrays.asList("华亭煤业", "扎煤公司", "陕西矿业", "庆阳煤电", "滇东公司");

            for (String key : sortOrder) {
                if (resultMap.containsKey(key)) {
                    String newKey = key.substring(0, 2);
                    updatedResultMap.put(newKey, resultMap.get(key));
                }
            }

        }
        else if ((type == 3 && level == 1)||(type == 3 && level == 2)||(type == 3 && level == 3)) {//矿
            for (MonthYieldVo monthYieldVo : monthYieldVos) {
                BigDecimal yearCumulativeCompletion = BigDecimal.ZERO;
                BigDecimal planOut = BigDecimal.ZERO;
                if(type == 3 && level == 1){
                    yearCumulativeCompletion = monthYieldVo.getYearCumulativeCompletion();
                    planOut = monthYieldVo.getPlanOutPuts();
                } else if (type == 3 && level == 2) {
                    yearCumulativeCompletion = monthYieldVo.getOutput();//月
                    planOut = monthYieldVo.getPlanOutput();
                }else{
                    yearCumulativeCompletion = monthYieldVo.getTodayQuantity();//日
                    planOut = monthYieldVo.getPlanOutputDay();
                }
                if (resultMap.containsKey(monthYieldVo.getMineName())) {
                    BigDecimal[] previousValue = resultMap.get(monthYieldVo.getMineName());
                    BigDecimal newActualValue = previousValue[0].add(yearCumulativeCompletion);
                    BigDecimal newPlanValue = previousValue[1].add(planOut);
                    resultMap.put(monthYieldVo.getMineName(), new BigDecimal[]{newActualValue, newPlanValue});
                } else {
                    resultMap.put(monthYieldVo.getMineName(), new BigDecimal[]{yearCumulativeCompletion, planOut});
                }
            }
            for (String mineName : CoalInfo.getAllMineName()) {
                if (!resultMap.containsKey(mineName)) {
                    resultMap.put(mineName, new BigDecimal[]{new BigDecimal("0"), new BigDecimal("0")});
                }
            }
            Map<String, BigDecimal[]> updatedResultMaps = new HashMap<>();
            for (Map.Entry<String, BigDecimal[]> entry : resultMap.entrySet()) {
                String key = entry.getKey().replaceAll("(公司|煤矿|露天矿|矿)$", "");
                updatedResultMaps.put(key, entry.getValue());
            }

            updatedResultMap.put("华亭煤矿", updatedResultMaps.get("华亭"));
            updatedResultMap.put("砚北煤矿", updatedResultMaps.get("砚北"));
            updatedResultMap.put("陈家沟煤矿", updatedResultMaps.get("陈家沟"));
            updatedResultMap.put("东峡煤矿", updatedResultMaps.get("东峡"));
//            updatedResultMap.put("马蹄沟", updatedResultMaps.get("马蹄沟"));
            updatedResultMap.put("山寨煤矿", updatedResultMaps.get("山寨"));
            updatedResultMap.put("新窑煤矿", updatedResultMaps.get("新窑"));
            updatedResultMap.put("新柏煤矿", updatedResultMaps.get("新柏"));
            updatedResultMap.put("大柳煤矿", updatedResultMaps.get("大柳"));
            updatedResultMap.put("赤城煤矿", updatedResultMaps.get("赤城"));
            updatedResultMap.put("灵泉煤矿", updatedResultMaps.get("灵泉"));
            updatedResultMap.put("铁北煤矿", updatedResultMaps.get("铁北"));
            updatedResultMap.put("灵东煤矿", updatedResultMaps.get("灵东"));
            updatedResultMap.put("灵露煤矿", updatedResultMaps.get("灵露"));
            updatedResultMap.put("西川煤矿", updatedResultMaps.get("西川"));
            updatedResultMap.put("青岗坪煤矿", updatedResultMaps.get("青岗坪"));
            updatedResultMap.put("柳巷煤矿", updatedResultMaps.get("柳巷"));
            updatedResultMap.put("核桃峪煤矿", updatedResultMaps.get("核桃峪"));
//            updatedResultMap.put("新庄煤矿", updatedResultMaps.get("新庄"));
//            updatedResultMap.put("刘园子", updatedResultMaps.get("刘园子"));
//            updatedResultMap.put("白龙山一井", updatedResultMaps.get("白龙山煤矿一井"));
//            updatedResultMap.put("雨汪一井", updatedResultMaps.get("雨汪煤矿一井"));
            updatedResultMap.put("魏家峁露天矿", updatedResultMaps.get("魏家峁"));
            updatedResultMap.put("高头窑煤矿", updatedResultMaps.get("高头窑"));
            updatedResultMap.put("铧尖露天矿", updatedResultMaps.get("铧尖"));
            updatedResultMap.put("伊敏露天矿", updatedResultMaps.get("伊敏"));
        }else {
            throw new HuaNengException(Constants.FAIL, "参数不正确");
        }
        //如果公司编码是扎煤，只返回扎煤下矿数据
        if (StringUtils.isNotEmpty(companyCode)) {
            if (companyCode.equalsIgnoreCase("91150781720169744B")) {
                Set<String> keysToKeep = new HashSet<>(Arrays.asList("灵露煤矿", "灵泉煤矿", "铁北煤矿", "灵东煤矿"));
                updatedResultMap.keySet().retainAll(keysToKeep);
            }
        }
        return updatedResultMap;
    }

    @Override
    public List<MonthOuputVO> getTrendProduction(Integer type, Integer level, String companyCode) {
        List<MonthOuputVO> monthOuputVOList = new ArrayList<>();
        LocalTime currentTime = LocalTime.now();
        Integer flag = null;
        if (currentTime.isAfter(LocalTime.of(0, 0)) && currentTime.isBefore(LocalTime.of(10, 0))) {
            System.out.println("当前时间在0点和10点之间");
            flag = 1;
        } else {
            System.out.println("当前时间不在0点和10点之间");
        }

        if((type == 1 && level == 1)){//近10年 煤炭产业
//            DynamicDataSourceContextHolder.push("dm");
            monthOuputVOList = groupStatisticMapper.recentlyTenYearsByIndustry();
//            DynamicDataSourceContextHolder.clear();


            for (MonthOuputVO outputVO : monthOuputVOList) {
                String yearMonth = outputVO.getYearMonth();
                // 根据年份进行判断和处理
                if (yearMonth.equals("2014")&&outputVO.getCompanyName().equals("总计")) {
                    outputVO.setOutput(new BigDecimal("7291"));
                } else if (yearMonth.equals("2015")&&outputVO.getCompanyName().equals("总计")) {
                    outputVO.setOutput(new BigDecimal("6151"));
                } else if (yearMonth.equals("2016")&&outputVO.getCompanyName().equals("总计")) {
                    outputVO.setOutput(new BigDecimal("6035"));
                } else if (yearMonth.equals("2017")&&outputVO.getCompanyName().equals("总计")) {
                    outputVO.setOutput(new BigDecimal("7064"));
                } else if (yearMonth.equals("2018")&&outputVO.getCompanyName().equals("总计")) {
                    outputVO.setOutput(new BigDecimal("7071"));
                }else if (yearMonth.equals("2019")&&outputVO.getCompanyName().equals("总计")) {
                    outputVO.setOutput(new BigDecimal("7324"));
                }else if (yearMonth.equals("2020")&&outputVO.getCompanyName().equals("总计")) {
                    outputVO.setOutput(new BigDecimal("7606"));
                } else if (yearMonth.equals("2021")&&outputVO.getCompanyName().equals("总计")) {
                    outputVO.setOutput(new BigDecimal("8661"));
                } else if (yearMonth.equals("2022")&&outputVO.getCompanyName().equals("总计")) {
                    outputVO.setOutput(new BigDecimal("10108"));
                }else if (yearMonth.equals("2023")&&outputVO.getCompanyName().equals("总计")) {
                    outputVO.setOutput(new BigDecimal("10800"));
                }
                // 可以依次类推处理每一年的逻辑
            }
        } else if (type == 2 && level==1) { //近12月  煤炭产业-------------
            monthOuputVOList = groupStatisticMapper.recentlyTwelveMonthsByIndustry();
        }else if(type == 3 && level==1){ //近30天  煤炭产业


            monthOuputVOList = groupStatisticMapper.recentlyThirtyDaysByIndustry(flag);
        }else if(type == 1 && level==2){//近10年 煤业公司
//            DynamicDataSourceContextHolder.push("dm");
            monthOuputVOList = groupStatisticMapper.recentlyTenYearsByCompany();

//            DynamicDataSourceContextHolder.clear();
            for (MonthOuputVO outputVO : monthOuputVOList) {
                String yearMonth = outputVO.getYearMonth();
                // 根据年份进行判断和处理
                if (yearMonth.equals("2014")&&outputVO.getCompanyName().equals("总计")) {
                    outputVO.setOutput(new BigDecimal("3960"));
                } else if (yearMonth.equals("2015")&&outputVO.getCompanyName().equals("总计")) {
                    outputVO.setOutput(new BigDecimal("3245"));
                } else if (yearMonth.equals("2016")&&outputVO.getCompanyName().equals("总计")) {
                    outputVO.setOutput(new BigDecimal("3095"));
                } else if (yearMonth.equals("2017")&&outputVO.getCompanyName().equals("总计")) {
                    outputVO.setOutput(new BigDecimal("3608"));
                } else if (yearMonth.equals("2018")&&outputVO.getCompanyName().equals("总计")) {
                    outputVO.setOutput(new BigDecimal("3774"));
                }else if (yearMonth.equals("2019")&&outputVO.getCompanyName().equals("总计")) {
                    outputVO.setOutput(new BigDecimal("3723"));
                }else if (yearMonth.equals("2020")&&outputVO.getCompanyName().equals("总计")) {
                    outputVO.setOutput(new BigDecimal("3853"));
                } else if (yearMonth.equals("2021")&&outputVO.getCompanyName().equals("总计")) {
                    outputVO.setOutput(new BigDecimal("3970"));
                } else if (yearMonth.equals("2022")&&outputVO.getCompanyName().equals("总计")) {
                    outputVO.setOutput(new BigDecimal("4261"));
                }else if (yearMonth.equals("2023")&&outputVO.getCompanyName().equals("总计")) {
                    outputVO.setOutput(new BigDecimal("4410"));
                }
                // 可以依次类推处理每一年的逻辑
                Map<String, Integer> indexMap = new HashMap<>();
                for (int i = 0; i < order.size(); i++) {
                    indexMap.put(order.get(i), i);
                }

                List<MonthOuputVO> sortedList = monthOuputVOList.stream()
                        .filter(vo -> !vo.getCompanyName().equals("滇东公司"))
                        .sorted(Comparator.comparingInt(vo -> indexMap.getOrDefault(vo.getCompanyName(), Integer.MAX_VALUE)))
                        .collect(Collectors.toList());
                monthOuputVOList = sortedList;
            }
        } else if (type == 2 && level ==2) { //近12 月 煤业公司
            monthOuputVOList = groupStatisticMapper.recentlyTwelveMonthsByCompany();
        } else if (type == 3 && level == 2) { //近30天 煤业公司
            monthOuputVOList = groupStatisticMapper.recentlyThirtyDaysByCompany(flag);
        }else {
            throw new HuaNengException(Constants.FAIL, "参数不正确");
        }
        return monthOuputVOList;
    }

    @Override
    public List<MonthOuputVO> getOutputYoy(Integer type, String companyCode) {
        List<MonthOuputVO> monthOuputVOList = new ArrayList<>();
        if((type == 1)){//近10年
            monthOuputVOList = groupStatisticMapper.getOutputYoyRecentlyTenYears(companyCode);
        } else if (type == 2) { //近12月
            monthOuputVOList = groupStatisticMapper.getOutputYoyrecentlyTwelveMonths(companyCode);
        }

        // 假设已经将数据填充到 monthOuputVOList 中

        for (int i = 1; i < monthOuputVOList.size(); i++) {
            MonthOuputVO current = monthOuputVOList.get(i);
            MonthOuputVO lastYear = monthOuputVOList.get(i - 1);

            if (lastYear.getOutput().compareTo(BigDecimal.ZERO) != 0 && current.getOutput()!=null && lastYear.getOutput()!=null) {
                BigDecimal growthRate = current.getOutput().subtract(lastYear.getOutput())
                        .divide(lastYear.getOutput(), 2, BigDecimal.ROUND_HALF_UP)
                        .multiply(new BigDecimal(100));
                current.setGrowthRate(growthRate);
            } else {
                current.setGrowthRate(new BigDecimal("0"));
            }
        }
        return monthOuputVOList;
    }

    @Override
    public List<MonthOuputVO> getSaleYoyandQoq(Integer type, String companyCode) {
        List<MonthOuputVO> monthOuputVOList = new ArrayList<>();
        if((type == 1)){//近10年
            monthOuputVOList = groupStatisticMapper.getSaleYoyRecentlyTenYears(companyCode);
        } else if (type == 2) { //近12月
            monthOuputVOList = groupStatisticMapper.getSaleYoyrecentlyTwelveMonths(companyCode);
        }

        // 假设已经将数据填充到 monthOuputVOList 中

        for (int i = 1; i < monthOuputVOList.size(); i++) {
            MonthOuputVO current = monthOuputVOList.get(i);
            MonthOuputVO lastYear = monthOuputVOList.get(i - 1);

            if (lastYear.getOutput().compareTo(BigDecimal.ZERO) != 0 && current.getOutput()!=null&& lastYear.getOutput()!=null) {
                BigDecimal growthRate = current.getOutput().subtract(lastYear.getOutput())
                        .divide(lastYear.getOutput(), 2, BigDecimal.ROUND_HALF_UP)
                        .multiply(new BigDecimal(100));
                current.setGrowthRate(growthRate);
            } else {
                current.setGrowthRate(new BigDecimal("0"));
            }
        }
        return monthOuputVOList;
    }

    @Override
    public List<CoalMiningTotalVo> getOutputSaleYoyandQoq(Integer type, String mineCode) {
        List<CoalMiningTotalVo> monthOuputVOList = new ArrayList<>();
        LocalTime currentTime = LocalTime.now();
        Integer mark = null;
        if (currentTime.isAfter(LocalTime.of(0, 0)) && currentTime.isBefore(LocalTime.of(9, 0))) {
            System.out.println("当前时间在0点和9点之间"+LocalTime.now());
            mark = 2;
        } else {
            System.out.println("当前时间不在0点和9点之间");
            mark = 1;
        }
        List<String> orderGroup1 = Arrays.asList("总计", "华亭", "扎煤", "陕西", "庆阳");
        List<String> orderGroup2 = Arrays.asList("总计","煤业公司", "北方公司", "蒙东公司");
        List<String> selectedOrder = null;
        DynamicDataSourceContextHolder.push("dm");
        if(type == 1||type == 2) {//近10年
            monthOuputVOList = groupStatisticMapper.getOutputSaleYoyandQoq(type, mark, mineCode);
        }else {
            throw new HuaNengException(Constants.FAIL, "参数不正确");
        }
        DynamicDataSourceContextHolder.clear();

        return monthOuputVOList;
    }

    @Override
    public List<MonthOuputVO> getMonthlyTrendOfExcavation(String mineCode, String type) {
        List<MonthOuputVO> list = groupStatisticMapper.getMonthlyTrendOfExcavation(mineCode, type);
        if (type.equals("2")) {
            for (MonthOuputVO v : list) {
                v.setOutput(v.getOutput() == null || v.getOutput().compareTo(BigDecimal.valueOf(0)) == 0 ? BigDecimal.valueOf(0) : v.getOutput());
            }
        }else{
            for (MonthOuputVO v : list) {
                v.setOutput(v.getOutput() == null || v.getOutput().compareTo(BigDecimal.valueOf(0)) == 0 ? BigDecimal.valueOf(0) : v.getOutput().divide(BigDecimal.valueOf(10000), 2, BigDecimal.ROUND_HALF_UP));
            }
        }
        return list;
    }

    @Override
    public  Map<String, String> getMineCode(String companyCode) {
        Map<String, String> codeNameMap = new HashMap<>();
        SysOrganizationVo sysOrganizationVo= RedisUtils.getCacheObject(Constants.SYS_CODESUB_KEY + "0");
        for (SysOrganizationVo s:sysOrganizationVo.getSubCodeList()){
            for(SysOrganizationVo s1 :s.getSubCodeList()){
                codeNameMap.put(s1.getOrgCode(), s1.getOrgName());
            }
        }

        //如果公司编码是扎煤，只返回扎煤下矿数据
        if (StringUtils.isNotEmpty(companyCode)) {
            if (companyCode.equalsIgnoreCase("91150781720169744B")) {
                Set<String> keysToKeep = new HashSet<>(Arrays.asList("150781013194", "150781013603", "150781013670", "150781013671"));
                codeNameMap.keySet().retainAll(keysToKeep);
            }
        }
        return codeNameMap;
    }
    @Override
    public  List<Map<String, String>> getMonthlySelect( String type) {
        DynamicDataSourceContextHolder.push("slave");
        List<Map<String, String>> monthlySelect = dimShiftMapper.getMonthlySelect( type);
//        List<Map<String, String>> monthlySelect = dimShiftMapper.getMonthlySelectFoo();
        DynamicDataSourceContextHolder.clear();
        return monthlySelect;
    }
    public  List<Map<String, String>> getMonthlySelectFoo(String mineName, String type) {
        DynamicDataSourceContextHolder.push("slave");
        List<Map<String, String>> monthlySelect = dimShiftMapper.getMonthlySelectFoo();
        DynamicDataSourceContextHolder.clear();
        return monthlySelect;
    }

    @Override
    public List<SaleAnalyseVo> compareYearMonthPlanActual(String type) {
        LocalTime currentTime = LocalTime.now();
        Integer flag = null;
        if (currentTime.isAfter(LocalTime.of(0, 0)) && currentTime.isBefore(LocalTime.of(10, 0))) {
            System.out.println("当前时间在0点和10点之间");
            flag = 1;
        } else {
            System.out.println("当前时间不在0点和10点之间");
        }
        List<SaleAnalyseVo> list = new ArrayList<>();
        list = groupStatisticMapper.compareYearMonthPlanActual(type,flag);
        if(!CollUtil.isNotEmpty(list)){
            flag = 1;
            list = groupStatisticMapper.compareYearMonthPlanActual(type,flag);

        }
        if (type.equals("1")) {
            for (SaleAnalyseVo v : list) {
                v.setPlan(v.getPlan() == null || v.getPlan().compareTo(BigDecimal.valueOf(0)) == 0 ? BigDecimal.valueOf(0) : v.getPlan().divide(BigDecimal.valueOf(10000), 2, BigDecimal.ROUND_HALF_UP));
                v.setMonthCount(v.getMonthCount() == null || v.getMonthCount().compareTo(BigDecimal.valueOf(0)) == 0 ? BigDecimal.valueOf(0) : v.getMonthCount().divide(BigDecimal.valueOf(10000), 2, BigDecimal.ROUND_HALF_UP));
                v.setYearPlan(v.getYearPlan() == null || v.getYearPlan().compareTo(BigDecimal.valueOf(0)) == 0 ? BigDecimal.valueOf(0) : v.getYearPlan().divide(BigDecimal.valueOf(10000), 2, BigDecimal.ROUND_HALF_UP));
                v.setYearCount(v.getYearCount() == null || v.getYearCount().compareTo(BigDecimal.valueOf(0)) == 0 ? BigDecimal.valueOf(0) : v.getYearCount().divide(BigDecimal.valueOf(10000), 2, BigDecimal.ROUND_HALF_UP));
            }
        }
//        List<Map<String, String>> monthlySelect = getMonthlySelect(null, null);
        List<Map<String, String>> monthlySelect = getMonthlySelectFoo(null, null);

        Map<String, String> mineNameMap = new HashMap<>();
        for (Map<String, String> map : monthlySelect) {
//            mineNameMap.put(map.get("minecode"), map.get("minename"));
            // 过滤条件：minename 不是 "马蹄沟" 和 "刘原子得"
            if (!"621022009406".equals(map.get("minecode")) && !"620824009852".equals(map.get("minecode"))) {
                mineNameMap.put(map.get("minecode"), map.get("minename"));
            }
        }

        for (SaleAnalyseVo vo : list) {

            String codePrefix = vo.getMineName().substring(0, 2); // 获取编号前两个字符
            for (Map.Entry<String, String> entry : mineNameMap.entrySet()) {
                String mineCode = entry.getKey(); // 这里应该是 getKey()，获取 map 中的键（minecode）
                String mineName = entry.getValue(); // 获取 map 中的值（minename）

                if (mineCode.startsWith(codePrefix)) { // 判断编号前两个字符是否匹配
                    vo.setMineName(mineName); // 替换名称
                    break; // 匹配成功后跳出循环
                }
            }
        }
        List<SaleAnalyseVo> filteredList = new ArrayList<>();

        for (SaleAnalyseVo vo : list) {
            vo.setMineName(CoalInfo.getMineNameByMineCode(vo.getMineCode()));
            vo.setMineName(vo.getMineName().replace("公司","煤矿"));
            if (vo.getMineName().equals("铁北矿")) {
                vo.setMineName("铁北煤矿");
            }
            if (vo.getMineName().equals("灵东矿")) {
                vo.setMineName("灵东煤矿");
            }
            if (vo.getMineName().equals("灵泉矿")) {
                vo.setMineName("灵泉煤矿");
            }
            if (vo.getMineName().equals("灵露矿")) {
                vo.setMineName("灵露煤矿");
            }
            if (vo.getMineName().equals("白龙山煤矿一井")) {
                vo.setMineName("白龙山一井");
            }
            if (vo.getMineName().equals("雨汪煤矿一井")) {
                vo.setMineName("雨汪一井");
            }
            if (!"621022009406".equals(vo.getMineCode()) && !"620824009852".equals(vo.getMineCode())) {
                filteredList.add(vo); // 如果 minename 不是 "马蹄沟" 和 "刘原子得"，则加入新的列表中
            }
        }
        String[] mineNames = {
                "华亭煤矿", "砚北煤矿", "陈家沟煤矿", "东峡煤矿", "马蹄沟",
                "山寨煤矿", "新窑煤矿", "新柏煤矿", "大柳煤矿", "赤城煤矿",
                "灵泉煤矿", "铁北煤矿", "灵东煤矿", "灵露煤矿", "西川煤矿",
                "青岗坪煤矿", "柳巷煤矿", "核桃峪煤矿", "新庄煤矿", "刘园子",
                "白龙山一井", "雨汪一井", "魏家峁露天矿", "高头窑煤矿", "铧尖露天矿",
                "伊敏露天矿"
        };
// 替换原始列表为过滤后的列表

        Comparator<SaleAnalyseVo> comparator = Comparator.comparingInt(item -> {
            String name = item.getMineName(); // 假设 SaleAnalyseVo 中有获取煤矿名称的方法
            for (int i = 0; i < mineNames.length; i++) {
                if (mineNames[i].equals(name)) {
                    return i;
                }
            }
            return mineNames.length; // 如果找不到，则排在最后
        });
        filteredList.sort(comparator);
        list = filteredList;
        return list;
    }

    @Override
    public List<MonthYieldVo> getDrivingStrippingStatus(String type) {
        LocalTime currentTime = LocalTime.now();
        Integer flag = null;
        if (currentTime.isAfter(LocalTime.of(0, 0)) && currentTime.isBefore(LocalTime.of(10, 0))) {
            System.out.println("当前时间在0点和10点之间");
            flag = 1;
        } else {
            System.out.println("当前时间不在0点和10点之间");
        }

        List<MonthYieldVo> list=groupStatisticMapper.getDrivingStrippingStatus(type,flag);
        if(type.equals("1")){
            for (MonthYieldVo item : list) {
                item.setPlanOutput(processBigDecimal(item.getPlanOutput()));
                item.setOutput(processBigDecimal(item.getOutput()));
                item.setPlanOutputDay(processBigDecimal(item.getPlanOutputDay()));
                item.setMonthOverabundance(processBigDecimal(item.getMonthOverabundance()));
                item.setYearOverabundance(processBigDecimal(item.getYearOverabundance()));
                item.setAvgOutput(processBigDecimal(item.getAvgOutput()));
                item.setYearCumulativePlan(processBigDecimal(item.getYearCumulativePlan()));
                item.setYearCumulativeCompletion(processBigDecimal(item.getYearCumulativeCompletion()));
                item.setYearPlan(processBigDecimal(item.getYearPlan()));
                item.setPlanOutPuts(processBigDecimal(item.getPlanOutPuts()));
                item.setBackCoal(processBigDecimal(item.getBackCoal()));
                item.setFootageMonth(processBigDecimal(item.getFootageMonth()));
                item.setPlanFootageMonth(processBigDecimal(item.getPlanFootageMonth()));
                item.setOutputYear(processBigDecimal(item.getOutputYear()));
                item.setTodayQuantity(processBigDecimal(item.getTodayQuantity()));
                item.setFootageYear(processBigDecimal(item.getFootageYear()));
                item.setShaleAmount(processBigDecimal(item.getShaleAmount()));
                item.setCoalSlime(processBigDecimal(item.getCoalSlime()));
                item.setStock(processBigDecimal(item.getStock()));
                item.setYearYoy(processBigDecimal(item.getYearYoy()));
                item.setMonthYoy(processBigDecimal(item.getMonthYoy()));
                item.setProvedOutput(processBigDecimal(item.getProvedOutput()));
                item.setWellProvedOutput(processBigDecimal(item.getWellProvedOutput()));
                item.setDewProvedOutput(processBigDecimal(item.getDewProvedOutput()));
            }
        }
        return list;
    }

    private BigDecimal processBigDecimal(BigDecimal value) {
        if (value != null && !BigDecimal.ZERO.equals(value)) {
            return value.divide(BigDecimal.valueOf(10000), 0, BigDecimal.ROUND_HALF_UP);
        }
        return value;
    }

    @Override
    public List<MonthYieldVo> getOutputStatus() {

        LocalTime currentTime = LocalTime.now();
        Integer flag = null;
        if (currentTime.isAfter(LocalTime.of(0, 0)) && currentTime.isBefore(LocalTime.of(10, 0))) {
            System.out.println("当前时间在0点和10点之间");
            flag = 1;
        } else {
            System.out.println("当前时间不在0点和10点之间");
        }
        return groupStatisticMapper.getOutputStatus(flag);
    }

    @Override
    public List<PlanStatisticVO> outputStatisticSituation(Integer type, String code) {

        Calendar start= Calendar.getInstance();
        start.setTime(new Date());

        start.add(Calendar.YEAR, -1);
        int dateYear = start.get(Calendar.YEAR);

        Calendar cal=Calendar.getInstance();
        cal.add(Calendar.DATE,-1);
        Date d = cal.getTime();
        Date[] dateRange = DateUtils.getDateRange(dateYear, null);
        List<PlanStatisticVO> list = new ArrayList<>();

        //type 1是公司 2是煤矿
        if (type== 1){
            BigDecimal lastYearOutputStatisticSituation = groupStatisticMapper.lastYearOutputStatisticSituation(dateRange[0], dateRange[1], type, code);
            BigDecimal lastYearOutputPlanStatisticSituation = groupStatisticMapper.lastYearOutputPlanStatisticSituation( dateRange[1], type, code);
            BigDecimal nowYearOutputPlanStatisticSituation = groupStatisticMapper.nowYearOutputPlanStatisticSituation( d, type, code);
            PlanStatisticVO nowYearProvedOutputPlanStatisticSituation = groupStatisticMapper.nowYearProvedOutputPlanStatisticSituation( d, type, code);
            if(nowYearProvedOutputPlanStatisticSituation==null){
                nowYearProvedOutputPlanStatisticSituation = new PlanStatisticVO();
            }
            nowYearProvedOutputPlanStatisticSituation.setLastYearPlan(lastYearOutputPlanStatisticSituation);
            nowYearProvedOutputPlanStatisticSituation.setLastYearOutPut(lastYearOutputStatisticSituation);
            nowYearProvedOutputPlanStatisticSituation.setNowYearPlan(nowYearOutputPlanStatisticSituation);
            list.add(nowYearProvedOutputPlanStatisticSituation);
        } else if (type==2) {
            list .addAll( groupStatisticMapper.lastYearAndNowYearOutputStatisticSituation(dateRange[0], dateRange[1], d, type));
            list.stream().distinct().forEach(item ->{
                item.setCompanyNames(item.getCompanyCode());
                item.setMineNames(item.getMineCode());
            });
        }

        return list;
    }

    @Override
    public List<PlanStatisticVO> laseDayOutputAndPlanStatisticSituation(Integer type, String code) {
        int daysOfMonth = DateUtils.getDaysOfMonth(new Date());
        Calendar cal=Calendar.getInstance();
        cal.add(Calendar.DATE,-1);
        Date d = cal.getTime();
        List<PlanStatisticVO> list = null;
        //查询剥离量
        if(type==1){
            BigDecimal peel = groupStatisticMapper.laseDayPeelStatistic(d, type, code);
            BigDecimal Footage = groupStatisticMapper.laseDayFootageStatistic(d, type, code);
            BigDecimal PlanFootage = groupStatisticMapper.laseDayPlanFootageStatistic(d, type, code);
            list = groupStatisticMapper.laseDayOutputAndPlanStatisticSituation(d, daysOfMonth,type, code);
            list.stream().distinct().forEach(item ->{
                if (item.getTypeName().equals("露天矿")){
                    item.setCompleteTotal(peel);
                }else{
                    item.setLastDayFootage(Footage);
                    item.setLastDayPlanFootage(PlanFootage);
                }
            });
        } else if (type==2) {
            List<PlanStatisticVO> list1 = groupStatisticMapper.laseDayPeelStatisticByMine(d, type, code);
            List<PlanStatisticVO> list2 = groupStatisticMapper.laseDayFootageStatisticByMine(d, type, code);
            list = groupStatisticMapper.laseDayOutputAndPlanStatisticSituationByMine(d, daysOfMonth,type, code);
            list.stream().distinct().forEach(item ->{
                list1.stream().distinct().forEach(item1 ->{
                    if(item.getMineCode().equals(item1.getMineCode())){
                        item.setCompleteTotal(item1.getCompleteTotal());
                    }
                });
                list2.stream().distinct().forEach(item2 ->{
                    if(item.getMineCode().equals(item2.getMineCode())){
                        item.setLastDayFootage(item2.getLastDayFootage());
                        item.setFootage(item2.getFootage());
                    }
                });
                item.setCompanyNames(item.getCompanyCode());
                item.setMineNames(item.getMineCode());
            });
        }else if (type==3) {
            List<PlanStatisticVO> list1 = groupStatisticMapper.laseDayPeelStatisticByCompany(d, type, code);
            list = groupStatisticMapper.laseDayOutputAndPlanStatisticSituation(d, daysOfMonth,type, code);
            if(list!=null){
                list.stream().distinct().forEach(item ->{
                    if(list1!=null){
                        list1.stream().distinct().forEach(item1 ->{
                            if(item.getCompanyCode().equals(item1.getCompanyCode())){
                                item.setCompleteTotal(item1.getCompleteTotal());
                            }
                        });
                    }
                    item.setCompanyNames(item.getCompanyCode());
                    item.setMineNames(item.getMineCode());
                });
            }
            Map<String, PlanStatisticVO> resultMap = list.stream()
                    .collect(Collectors.toMap(
                            PlanStatisticVO::getCompanyCode,
                            vo -> vo,
                            (existing, replacement) -> {
                                existing.setLaseDayOutput(existing.getLaseDayOutput().add(replacement.getLaseDayOutput()));
                                return existing;
                            }
                    ));

            // 将结果 Map 转换回 List
            List<PlanStatisticVO> mergedList = resultMap.values().stream().collect(Collectors.toList());
            list = mergedList;
        }

        return list;
    }

    @Override
    public SaleAnalyseVo saleAnalyse(SaleAnalyseReq req) {

        SaleAnalyseVo saleAnalyseVoYear = groupStatisticMapper.yearSaleAnalyse(null);
        SaleAnalyseVo saleAnalyseVoMonth = groupStatisticMapper.monthSaleAnalyse(null);

        SaleAnalyseVo v = new SaleAnalyseVo();
        v.setYearPlan(saleAnalyseVoYear.getPlan());
        v.setYearSale(saleAnalyseVoYear.getSale());
        v.setPlan(saleAnalyseVoMonth.getPlan());
        v.setSale(saleAnalyseVoMonth.getSale());

        if (saleAnalyseVoMonth.getPlan().compareTo(new BigDecimal(0)) != 0) {
            v.setMonthCount(saleAnalyseVoMonth.getSale().divide(saleAnalyseVoMonth.getPlan(), 4, ROUND_CEILING).multiply(new BigDecimal(100)));
        } else {
            v.setMonthCount(new BigDecimal(0));
        }
        if (saleAnalyseVoYear.getPlan().compareTo(new BigDecimal(0)) != 0) {
            v.setYearCount(saleAnalyseVoYear.getSale().divide(saleAnalyseVoYear.getPlan(), 4, ROUND_CEILING).multiply(new BigDecimal(100)));
        } else {
            v.setYearCount(new BigDecimal(0));
        }
        return v;
    }


    @Override
    public List<SaleAnalyseVo> saleAnalyseSubmenu(SaleAnalyseReq req) {

        Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH) + 1;
        Date[] dateRange = DateUtils.getDateRange(DateUtil.year(new Date()), null);
        Date monthLastDay = DateUtils.getDateRange(year, req.getMonth() == 0 ? 12 : req.getMonth())[1];
        Date[] monthDateRange = DateUtils.getDateRange(DateUtil.year(new Date()), req.getMonth() == 0 ? month : req.getMonth());

        Date param1;
        Date param2;
        param1 = dateRange[0];
        param2 = dateRange[1];
//        if (StrUtil.isBlank(req.getType())) {
//            //年 第一天和最后一天
//            param1 = dateRange[0];
//            param2 = dateRange[1];
//        } else if (req.getType().equals("1")) {
//            //月 第一天和最后一天
//            param1 = monthDateRange[0];
//            param2 = monthDateRange[1];
//        } else {
//            //年 第一天和当月最后一天
//            param1 = dateRange[0];
//            param2 = monthLastDay;
//
//        }
        List<SaleAnalyseVo> saleAnalyseVoList = groupStatisticMapper.saleAnalyseSubmenu(param1, param2,monthDateRange[0],monthDateRange[1], req.getCompanyCode());
        saleAnalyseVoList.forEach(sale->{
            sale.setMineName(CoalInfo.getMineNameByMineCode(sale.getMineCode()));
            sale.setCompanyName(CoalInfo.getCompanyNameByMineCode(sale.getMineCode()));
            sale.setYearSaleNew(sale.getYearSaleNew()==null?new BigDecimal(0):sale.getYearSaleNew().divide(BigDecimal.valueOf(10000),2, ROUND_HALF_UP));
            sale.setMonthSale(sale.getMonthSale()==null?new BigDecimal(0):sale.getMonthSale().divide(BigDecimal.valueOf(10000),2, ROUND_HALF_UP));
        });
        return saleAnalyseVoList;
    }

    @Override
    public Map<String, String[]> productionAndMarketingCount(String companyCode) {
        List<ProductionAndMarketingVo> list=groupStatisticMapper.productionAndMarketingCount(companyCode);

        String[] datas = new String[list.size()];
        String[] salesVolume = new String[list.size()];
        String[] yieldVolume = new String[list.size()];
        String[] mass = new String[list.size()];

        for (int i = 0; i < list.size(); i++) {
            datas[i]=list.get(i).getMonth()+"月";
            salesVolume[i]=list.get(i).getSalesVolume().divide(BigDecimal.valueOf(10000),2, ROUND_CEILING)+"";
            yieldVolume[i]=list.get(i).getYieldVolume().divide(BigDecimal.valueOf(10000),2, ROUND_CEILING)+"";
            mass[i]=list.get(i).getMass().divide(BigDecimal.valueOf(10000),2, ROUND_CEILING)+"";
        }

        Map<String, String[]> map = new HashMap<>();
        map.put("month",datas);
        map.put("salesVolume",salesVolume);
        map.put("yieldVolume",yieldVolume);
        map.put("mass",mass);

        return map;
    }


    @Override
    public List<ProductionAndMarketingVo> productionAndMarketingCountSubmenu(SaleAnalyseReq req) {
        Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        Date[] dateRange = DateUtils.getDateRange(DateUtil.year(new Date()), null);
        Date[] monthDateRange = DateUtils.getDateRange(DateUtil.year(new Date()), req.getMonth() == 0 ? null : req.getMonth());

        Date param1;
        Date param2;
        if (req.getMonth() == 0) {
            //年 第一天和最后一天
            param1 = dateRange[0];
            param2 = dateRange[1];
        } else {
            //月 第一天和当月最后一天
            param1 = monthDateRange[0];
            param2 = monthDateRange[1];

        }
        List<ProductionAndMarketingVo> list = groupStatisticMapper.productionAndMarketingCountSubmenu(param1, param2, req.getCompanyCode());
        list.forEach(l -> {
            l.setMineName(CoalInfo.getMineNameByMineCode(l.getMineCode()));
            l.setCompanyName(CoalInfo.getCompanyNameByMineCode(l.getMineCode()));
            l.setSalesVolume(l.getSalesVolume() == null ? BigDecimal.valueOf(0) : l.getSalesVolume().divide(BigDecimal.valueOf(10000), 2, ROUND_HALF_UP));
            l.setYieldVolume(l.getYieldVolume() == null ? BigDecimal.valueOf(0) : l.getYieldVolume().divide(BigDecimal.valueOf(10000), 2, ROUND_HALF_UP));
        });
        return list;
    }

    @Override
    public OpencastAndUndergroundMiningVo opencastAndUndergroundMiningCount(String companyCode,String type) {

        OpencastAndUndergroundMiningReq req = new OpencastAndUndergroundMiningReq();
        req.setCompanyCode(companyCode);
        req.setType(type);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        //年，第一天和最后一天
        Date[] yearDates=DateUtils.getDateRange(null,null);
        req.setYearBeginDate(yearDates[0]);
        req.setYearEndDate(yearDates[1]);
        //月，第一天和最后一天
        Date[] monthDates = DateUtils.getDateRange(null,calendar.get(Calendar.MONTH) + 1);
        req.setMonthBeginDate(monthDates[0]);
        req.setMonthEndDate(monthDates[1]);
        //周，第一天和最后一天
        Date[] weekDates = DateUtils.getweek(0, new Date());
        req.setWeekBeginDate(weekDates[0]);
        req.setWeekEndDate(weekDates[1]);

        OpencastAndUndergroundMiningVo v=groupStatisticMapper.opencastAndUndergroundMiningCount(req);

        //当前年天数
        BigDecimal numOfDays = new BigDecimal(calendar.getActualMaximum(Calendar.DAY_OF_YEAR));
        //当前月天数
        BigDecimal monthDays=new BigDecimal(DateUtils.getDaysOfMonth(new Date()));

        //周计划产量
        v.setWeekPlanYield(v.getYearYieldPlan()==null?new BigDecimal(0):v.getYearYieldPlan().divide(numOfDays,4,ROUND_HALF_UP).multiply(new BigDecimal(7)));
        //月计划产量
        v.setMonthPlanYield(v.getYearYieldPlan()==null?new BigDecimal(0):v.getYearYieldPlan().divide(numOfDays,4,ROUND_HALF_UP).multiply(monthDays));

        //周计划剥离量
        v.setWeekPlanPeel(v.getMonthPlanPeel()==null?new BigDecimal(0):v.getMonthPlanPeel().divide(numOfDays,4,ROUND_HALF_UP).multiply(new BigDecimal(7)));
        //月计划剥离量
//        v.setMonthPlanPeel(v.getMonthPlanPeel()==null?new BigDecimal(0):v.getMonthPlanPeel());
        return v;
    }

    @Override
    public List<OpencastAndUndergroundMiningVo> opencastAndUndergroundMiningCountSubmenu(String companyCode,String type) {
        OpencastAndUndergroundMiningReq req = new OpencastAndUndergroundMiningReq();
        req.setCompanyCode(companyCode);
        req.setType(type);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        //年，第一天和最后一天
        Date[] yearDates=DateUtils.getDateRange(null,null);
        req.setYearBeginDate(yearDates[0]);
        req.setYearEndDate(yearDates[1]);
        //月，第一天和最后一天
        Date[] monthDates = DateUtils.getDateRange(null,calendar.get(Calendar.MONTH) + 1);
        req.setMonthBeginDate(monthDates[0]);
        req.setMonthEndDate(monthDates[1]);
        //周，第一天和最后一天
        Date[] weekDates = DateUtils.getweek(0, new Date());
        req.setWeekBeginDate(weekDates[0]);
        req.setWeekEndDate(weekDates[1]);

        List<OpencastAndUndergroundMiningVo> vList= null;
        if (StrUtil.isNotBlank(req.getType())&&req.getType().equals("1")) {
            vList = groupStatisticMapper.opencastAndUndergroundMiningCountSubmenu(req);
        }else if(StrUtil.isNotBlank(req.getType())&&req.getType().equals("2")){
            vList = groupStatisticMapper.opencastAndUndergroundMiningCountSubmenuTypeTwo(req);
        }

            //当前年天数
        BigDecimal numOfDays = new BigDecimal(calendar.getActualMaximum(Calendar.DAY_OF_YEAR));
        //当前月天数
        BigDecimal monthDays=new BigDecimal(DateUtils.getDaysOfMonth(new Date()));
//        new BigDecimal(10000),4,ROUND_HALF_UP
        if (vList!=null&&vList.size()!=0) {
            vList.forEach(v -> {

                v.setCompanyName(CoalInfo.getCompanyNameByMineCode(v.getMineCode()));

                v.setWeekPeel(v.getWeekPeel() == null ? new BigDecimal(0) : v.getWeekPeel().divide(new BigDecimal(10000), 2, ROUND_HALF_UP));
                v.setWeekYield(v.getWeekYield() == null ? new BigDecimal(0) : v.getWeekYield().divide(new BigDecimal(10000), 2, ROUND_HALF_UP));
                v.setWeekPlanDriving(v.getWeekPlanDriving() == null ? new BigDecimal(0) : v.getWeekPlanDriving().divide(new BigDecimal(10000), 2, ROUND_HALF_UP));
                v.setWeekDriving(v.getWeekDriving() == null ? new BigDecimal(0) : v.getWeekDriving().divide(new BigDecimal(10000), 2, ROUND_HALF_UP));


                v.setMonthDriving(v.getMonthDriving() == null ? new BigDecimal(0) : v.getMonthDriving().divide(new BigDecimal(10000), 2, ROUND_HALF_UP));
                v.setMonthPeel(v.getMonthPeel() == null ? new BigDecimal(0) : v.getMonthPeel().divide(new BigDecimal(10000), 2, ROUND_HALF_UP));
                v.setMonthYield(v.getMonthYield() == null ? new BigDecimal(0) : v.getMonthYield().divide(new BigDecimal(10000), 2, ROUND_HALF_UP));
                v.setMonthPlanDriving(v.getMonthPlanDriving() == null ? new BigDecimal(0) : v.getMonthPlanDriving().divide(new BigDecimal(10000), 2, ROUND_HALF_UP));

                v.setYearPeelPlan(v.getYearPeelPlan() == null ? new BigDecimal(0) : v.getYearPeelPlan().divide(new BigDecimal(10000), 2, ROUND_HALF_UP));
                v.setYearYield(v.getYearYield() == null ? new BigDecimal(0) : v.getYearYield().divide(new BigDecimal(10000), 2, ROUND_HALF_UP));
                v.setYearYieldPlan(v.getYearYieldPlan() == null ? new BigDecimal(0) : v.getYearYieldPlan().divide(new BigDecimal(10000), 2, ROUND_HALF_UP));

                //周计划产量
                v.setWeekPlanYield(v.getYearYieldPlan() == null ? new BigDecimal(0) : v.getYearYieldPlan().divide(numOfDays, 4, ROUND_HALF_UP).multiply(new BigDecimal(7)).divide(new BigDecimal(10000), 2, ROUND_HALF_UP));
                //月计划产量
                v.setMonthPlanYield(v.getYearYieldPlan() == null ? new BigDecimal(0) : v.getYearYieldPlan().divide(numOfDays, 4, ROUND_HALF_UP).multiply(monthDays).divide(new BigDecimal(10000), 2, ROUND_HALF_UP));
                //周计划剥离量
                v.setWeekPlanPeel(v.getYearPeelPlan() == null ? new BigDecimal(0) : v.getYearPeelPlan().divide(numOfDays, 4, ROUND_HALF_UP).multiply(new BigDecimal(7)).divide(new BigDecimal(10000), 2, ROUND_HALF_UP));
                //月计划剥离量
                v.setMonthPlanPeel(v.getYearPeelPlan() == null ? new BigDecimal(0) : v.getYearPeelPlan().divide(numOfDays, 4, ROUND_HALF_UP).multiply(monthDays).divide(new BigDecimal(10000), 2, ROUND_HALF_UP));
            });
        }
        return vList;
    }

    /**
     * 构建对象
     *
     * @param dataType 计划类型
     * @param plan     计划量
     * @param complete 完成量
     * @return 数据统计结果
     */
    private PlanStatisticVO createPlanComplete(DataType dataType, BigDecimal plan, BigDecimal complete, int scale, RoundingMode mode) {
        PlanStatisticVO vo = new PlanStatisticVO();
        vo.setDataCode(dataType.name());
        vo.setDataName(dataType.getDesc());
        vo.setPlanTotal(plan.setScale(scale, mode));
        vo.setCompleteTotal(complete.setScale(scale, mode));
        vo.setPercent(vo.getPlanTotal().compareTo(BigDecimal.ZERO) == 0 ? Constants.ZERO : vo.getCompleteTotal().multiply(Constants.HUNDRED).divide(vo.getPlanTotal(), scale, mode));
        return vo;
    }

    /**
     * 构建对象
     *
     * @param dataType 计划类型
     * @param plan     计划量
     * @param complete 完成量
     * @return 数据统计结果
     */
    private PlanStatisticVO createPlanComplete(DataType dataType, BigDecimal plan, BigDecimal complete) {
        return createPlanComplete(dataType, plan, complete, 2, RoundingMode.CEILING);
    }

    @Override
    public Map<String,Object> getFillingAnalysis(String dateStr, String type, int pageNum, int pageSize,String companyCode) {
        Map<String, Object> map = new HashMap<>();
        List<FillingAnalysisVo> listVo = new ArrayList<>();
        //获取某月第一天和最后一天
//        String [] s=DateUtils.getMonthFirstAndLastDays("2023-04");
//        String [] dates=DateUtils.getMonthDays("2023-04");
        //查询数据库，返回公司编码和数据日期
//        List<ExecutionFootageOutputVO> list=groupStatisticMapper.getFillingAnalysis(s[0],s[1]);
        //分别统计各公司从某月第一天到最后一天是否有数据
        Set<String> companyCodes = new HashSet<>();
        if(StrUtil.isNotBlank(companyCode)){
            companyCodes.add(companyCode);
        }else{
            companyCodes= CoalInfo.getCompanyCodes();

        }
//        Set<String> companyCodes = new HashSet<>();
//        companyCodes.add("91150100767874571R");

        for (String c : companyCodes) {
            listVo = getFillingInfo(listVo, c, dateStr);
        }


        //
        if (StrUtil.isNotBlank(type) && type.equals("1")) {
            listVo = listVo.stream().sorted(Comparator.comparing(FillingAnalysisVo::getStatisticalType).reversed()).collect(Collectors.toList());
        }
        map.put("totalNumber",listVo.size());


        //最大页数
        int pageCount = (int) Math.ceil((double) listVo.size() / pageSize);
        //结束最大下标
        int maxSize = (pageNum + 1) * pageSize > listVo.size() ? listVo.size() : (pageNum + 1) * pageSize;
        //页数
        pageNum = (pageNum + 1) > pageCount ? pageCount : (pageNum + 1);

        listVo = listVo.subList((pageNum - 1) * pageSize, maxSize);

        map.put("currentNumber",listVo.size());
        map.put("maxPageNum",pageCount);
        map.put("data", listVo);
        return map;
    }

    public List<FillingAnalysisVo> getFillingInfo(List<FillingAnalysisVo> listVo, String companyCode, String dateStr) {

        String[] dates = DateUtils.getMonthDays(dateStr);

        FillingAnalysisVo coalYiel = new FillingAnalysisVo();
        coalYiel.setStatisticalType("煤炭产量");
        coalYiel.setCompanyName(CoalInfo.getCompanyNameByCompanyCode(companyCode));

        FillingAnalysisVo drivingFootage = new FillingAnalysisVo();
        drivingFootage.setStatisticalType("掘进进尺");
        drivingFootage.setCompanyName(CoalInfo.getCompanyNameByCompanyCode(companyCode));

        FillingAnalysisVo peelAmount = new FillingAnalysisVo();
        peelAmount.setStatisticalType("剥离量");
        peelAmount.setCompanyName(CoalInfo.getCompanyNameByCompanyCode(companyCode));

        String[] isF = new String[dates.length];
        //剥离量
        String falseFilling[] = new String[dates.length];

        List<ExecutionFootageOutputVO> list = groupStatisticMapper.getFillingAnalysis(dates[0], dates[dates.length - 1]);

        for (int i = 0; i < dates.length; i++) {
            falseFilling[i] = "0";
            boolean isMate = false;
            for (int j = 0; j < list.size(); j++) {
                if (list.get(j).getCompanyCode().equals(companyCode)) {

                    if (dates[i].equals(new SimpleDateFormat("yyyy-MM-dd").format(list.get(j).getExecutionDate()))) {
                        isF[i] = "1";
                        isMate = true;
                        break;
                    }
                }
            }
            if (!isMate) {
                isF[i] = "0";
            }
        }

        coalYiel.setIsFilling(isF);
        drivingFootage.setIsFilling(isF);
        peelAmount.setIsFilling(falseFilling);
        listVo.add(coalYiel);
        listVo.add(drivingFootage);
        listVo.add(peelAmount);

        return listVo;
    }

    @Override
    public List<CompanyYearTotalYieldVo> companyYearTotalYield() {

        List<OpencastAndUndergroundMiningVo> vList = opencastAndUndergroundMiningCountSubmenu(null, "1");
        List<OpencastAndUndergroundMiningVo> tList = opencastAndUndergroundMiningCountSubmenu(null, "2");

        // 合并vList和tList，并根据公司名称分组并对每组的年产量求和
        Map<String, BigDecimal> mergedCompanyYearYieldMap = Stream.concat(vList.stream(), tList.stream())
                .collect(Collectors.groupingBy(OpencastAndUndergroundMiningVo::getCompanyName,
                        Collectors.mapping(OpencastAndUndergroundMiningVo::getYearYield,
                                Collectors.reducing(BigDecimal.ZERO, BigDecimal::add))));

        // 将结果封装成新的对象并添加到新的List中
        List<CompanyYearTotalYieldVo> companyYearYieldList = mergedCompanyYearYieldMap.entrySet().stream()
                .map(entry -> new CompanyYearTotalYieldVo(entry.getKey(), entry.getValue()))
                .collect(Collectors.toList());
        return companyYearYieldList;
    }

    @Override
    public List<MineNumberVo> getMineNumberStatus(String companyCode) {
        List<MineNumber> list=groupStatisticMapper.getMineNumber(companyCode);
        return list.stream()
                .map(mineNumber -> {
                    String status;
                    if (mineNumber.getIsProduction().equals("0")) {
                        status = "基建";
                    } else if (mineNumber.getIsProduction().equals("1")) {
                        status = "生产";
                    } else {
                        status = "停产";
                    }
//                    String name = mineNumber.getMineName() + "煤矿，状态" + status;
                    return new MineNumberVo(mineNumber.getMineName(),status);
                })
                .collect(Collectors.toList());

    }

    @Override
    public MineNumberVo getMineNumber(String companyCode) {
        List<MineNumber> list=groupStatisticMapper.getMineNumber(companyCode);

        MineNumberVo vo=new MineNumberVo();
        vo.setMineNumber(list.size());
        for (MineNumber n:list) {
            if(n.getIsProduction().equals("1"))vo.setProductionMine(vo.getProductionMine()+1);
            if(n.getIsProduction().equals("2"))vo.setIiscontinuedMine(vo.getIiscontinuedMine()+1);
            if(n.getIsProduction().equals("0"))vo.setInfrastructureMine(vo.getInfrastructureMine()+1);
            if(n.getType().equals("1"))vo.setWellMine(vo.getWellMine()+1);
            if(n.getType().equals("0"))vo.setStripMine(vo.getStripMine()+1);
        }

        return vo;
    }
}
